import 'dart:developer';

import 'package:dio/dio.dart';
import 'package:edu/constants/app_strings.dart';
import 'package:edu/networks/account/models/user_response.dart';
import 'package:edu/utils/account_info.dart';
import 'package:edu/utils/data_fetcher.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

class ProfessionSettingPageLogic extends ChangeNotifier {
  List<Profession>? professions;
  bool isLoading = false;
  bool isError = false;

  bool get isProfessionsEmpty => professions?.isEmpty ?? true;
  String? currentProfessionName;

  late final _cancelToken = CancelToken();

  void init() {
    currentProfessionName = AccountInfo.shared.userProfile?.profession;

    // // 延迟加载
    // Future.delayed(Duration.zero, () {
    loadAllProfessions();
    // });
  }

  @override
  void dispose() {
    _cancelToken.cancel();
    super.dispose();
  }

  void loadAllProfessions() async {
    try {
      EasyLoading.show(
        indicator: const CircularProgressIndicator(),
        maskType: EasyLoadingMaskType.clear,
        dismissOnTap: false,
      );
      isLoading = true;
      isError = false;
      notifyListeners();

      final response = await DataFetcher.shared.userApi.getAllProfessions(
        cancelToken: _cancelToken,
      );

      isLoading = false;
      EasyLoading.dismiss();
      if (response.code == 0 && response.professions != null) {
        professions = response.professions;
      } else if (response.code != 0) {
        isError = true;
        EasyLoading.showError(response.message ?? AppStrings.unknownError);
      }
      notifyListeners();
    } on DioException catch (e) {
      EasyLoading.dismiss();
      // 请求被取消
      if (e.type == DioExceptionType.cancel) {
        log('Request cancelled:${e.message}');
        return;
      }
      isLoading = false;
      isError = true;
      notifyListeners();
      EasyLoading.showError(e.toString());
    } catch (e) {
      log('${AppStrings.unknownError}: $e');
    }
  }

  /*
   * 更新职业
   */
  Future<bool> updateProfession() async {
    if (currentProfessionName == AccountInfo.shared.userProfile?.profession) {
      return true;
    }

    // 获取目标职业
    final targetProfession = professions?.firstWhere(
      (profession) => profession.title == currentProfessionName,
    );
    // 获取目标职业的id
    final targetId = targetProfession?.id;
    if (targetId == null) {
      return false;
    }

    try {
      EasyLoading.show(
        indicator: const CircularProgressIndicator(),
        maskType: EasyLoadingMaskType.black,
        dismissOnTap: false,
      );
      final response = await DataFetcher.shared.userApi.updateUserProfession(
        targetId,
      );
      EasyLoading.dismiss();
      if (response.code == 0 && response.result?.field == 'profession') {
        EasyLoading.showSuccess(AppStrings.updateSuccess);
        AccountInfo.shared.updateProfession(response.result?.value);
        return true;
      } else {
        EasyLoading.showError(response.message ?? AppStrings.unknownError);
        return false;
      }
    } catch (e) {
      EasyLoading.dismiss();
      EasyLoading.showError(e.toString());
      log('更新职业失败: $e');
      return false;
    }
  }

  /*
   * 选择职业
   */
  void selectProfession(int index) {
    // 数据为空
    if (professions == null) {
      return;
    }
    // 索引越界
    if (index < 0 || index >= professions!.length) {
      return;
    }
    currentProfessionName = professions![index].title;
    notifyListeners();
  }
}
